package com.lee.algorithm.hash;

/***
 * @description: 用基本数据类型模拟 BitMap
 * @author : 博客园 @ 青石路
 * @date: 2022/1/3 19:34
 */
public class BitMap {

    public static void main(String[] args) {

        // 4 字节，32 bit
        int a = 0;

        // 32 bit * 10 = 320 bit
        // arr[0]: 0 ~ 31，arr[1]: 32 ~ 63，...
        int[] arr = new int[10];

        setOne(arr, 8);
        int s = get(arr, 8);
        System.out.println(s);
        setZero(arr, 8);
        s = get(arr, 8);
        System.out.println(s);
    }

    /**
     * bit 位设置成 0
     * @param position
     */
    public static void setZero(int[] arr, int position) {
        int elemIndex = position / 32;
        int bitIndex = position % 32;
        arr[elemIndex] = arr[elemIndex] & (~ (1 << bitIndex));
    }

    /**
     * bit 位设置成 1
     * @param arr
     * @param position
     */
    public static void setOne(int[] arr, int position) {
        int elemIndex = position / 32;
        int bitIndex = position % 32;
        arr[elemIndex] = arr[elemIndex] | (1 << bitIndex);
    }

    /**
     * 取 bit 位
     * @param arr
     * @param position
     * @return
     */
    public static int get(int[] arr, int position) {
        int elemIndex = position / 32;
        int bitIndex = position % 32;
        return (arr[elemIndex] >> bitIndex ) & 1;
    }
}
